<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px"
      @submit.native.prevent>
      <el-form-item label="城市名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入城市名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查找</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['base:station:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['base:station:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['base:station:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['base:station:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-upload" size="mini" @click="handleImport"
          v-hasPermi="['base:station:add']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="showImportError" type="danger" plain icon="el-icon-download" size="mini"
          @click="handleExportErrorData">导出错误数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="showImportError" type="danger" plain icon="el-icon-document-copy" size="mini"
          @click="handleCopyErrorData">复制到剪贴板</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleClear"
          v-hasPermi="['base:station:remove']">清空数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stationList" :row-style="{ height: '60px' }"
      @selection-change="handleSelectionChange">
      <el-table-column show-overflow-tooltip type="selection" width="55" align="center" />
      <el-table-column show-overflow-tooltip label="id" align="center" prop="id" />
      <el-table-column show-overflow-tooltip label="城市" align="center" prop="name" />
      <el-table-column show-overflow-tooltip label="城市拼音" align="center" prop="namePinyin" />
      <el-table-column show-overflow-tooltip label="城市首字母" align="center" prop="namePy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['base:station:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['base:station:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改车站管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="城市" prop="name">
          <el-input v-model="form.name" placeholder="请输入站名" @input="handleNameChange" />
        </el-form-item>
        <el-form-item label="城市拼音" prop="namePinyin">
          <el-input v-model="form.namePinyin" placeholder="请输入城市拼音" :disabled="true" />
        </el-form-item>
        <el-form-item label="城市首字母" prop="namePy">
          <el-input v-model="form.namePy" placeholder="请输入城市首字母" :disabled="true" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="title" :visible.sync="importOpen" width="400px" append-to-body>
      <div class="import-tip" style="margin-bottom: 15px;">
        <p style="margin: 0 0 10px 0;">请按以下格式准备Excel文件：</p>
        <el-card class="box-card" shadow="never">
          <div class="text item">
            <p style="margin: 5px 0;">1. 城市（必填）：如 北京</p>
            <p style="margin: 5px 0;">2. 城市拼音（选填）：如 beijing</p>
            <p style="margin: 5px 0;">3. 城市首字母（选填）：如 bj</p>
          </div>
        </el-card>
        <div style="margin-top: 10px; display: flex; gap: 10px;">
          <el-link type="primary" @click="showExampleImage">
            查看Excel模板示例
          </el-link>
          <el-link type="primary" @click="handleDownloadTemplate">
            下载Excel模板
          </el-link>
        </div>
      </div>
      <!-- 原有的上传组件 -->
      <el-upload ref="upload" class="upload-demo" :action="uploadExcelUrl" :headers="headers"
        :on-success="handleExcelSuccess" :on-error="handleExcelError" :auto-upload="false" :before-upload="beforeUpload"
        :limit="1" :on-exceed="handleExceed" :on-change="handleFileChange" accept=".xlsx, .xls">
        <el-button slot="trigger" size="small" type="primary">上传文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload"
          :disabled="!fileSelected">上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件，且不超过5MB</div>
      </el-upload>
    </el-dialog>

    <!-- 添加示例图片对话框 -->
    <el-dialog title="Excel模板示例" :visible.sync="exampleImageVisible" width="460px" :margin="0" :append-to-body="true"
      custom-class="zero-padding-dialog">
      <div style="padding: 0; overflow-x: hidden;">
        <table class="compact-table">
          <thead>
            <tr>
              <th width="160">id</th>
              <th width="70">城市</th>
              <th width="100">城市拼音</th>
              <th width="70">首字母</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>1890636568357368878</td>
              <td>北京</td>
              <td>beijing</td>
              <td>bj</td>
            </tr>
          </tbody>
        </table>
      </div>
    </el-dialog>

    <!-- 导入错误对话框 - 暂时保留但不使用 -->
    <el-dialog title="导入错误数据" :visible.sync="importErrorVisible" width="850px" append-to-body
      custom-class="import-error-dialog" v-if="false">
      <!-- 对话框内容已移除，因为现在直接在主页面上提供导出错误数据和复制到剪贴板功能 -->
    </el-dialog>

    <!-- 密码验证对话框 -->
    <el-dialog title="密码验证" :visible.sync="passwordDialogVisible" width="400px" append-to-body>
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="80px">
        <el-form-item label="密码" prop="password">
          <el-input v-model="passwordForm.password" type="password" placeholder="请输入当前用户密码" show-password></el-input>
          <div class="warning-text">提示：清空操作不可恢复，请谨慎操作！</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClosePasswordDialog">取 消</el-button>
        <el-button type="primary" @click="submitPassword">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStation, getStation, delStation, addStation, updateStation, clearStation } from "@/api/base/station";
import { pinyin } from 'pinyin-pro';

export default {
  name: "Station",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中数组
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车站管理表格数据
      stationList: [],
      // 弹出层标题
      title: "",
      // 示例图片对话框
      exampleImageVisible: false,
      exampleData: [{
        id: '1890636568357368878',
        name: '北京',
        namePinyin: 'beijing',
        namePy: 'bj'
      }],
      // 是否显示弹出层
      open: false,
      // 导入对话框
      importOpen: false,
      //上传地址
      uploadExcelUrl: process.env.VUE_APP_BASE_API + "/base/station/importExcel",
      //请求头
      headers: { 'Authorization': 'Bearer ' + this.$store.getters.token },
      //禁止上传按钮
      fileSelected: false,
      // 查询参数
      queryParams: {
        name: null,
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "城市名称不能为空", trigger: "blur" }
        ],
      },
      // 导入错误数据
      importErrorData: [],
      // 是否显示导入错误按钮
      showImportError: false,
      // 导入错误对话框可见性
      importErrorVisible: false,
      // 密码验证对话框
      passwordDialogVisible: false,
      passwordForm: {
        password: ''
      },
      passwordRules: {
        password: [
          { required: true, message: "请输入密码", trigger: "blur" }
        ]
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 下载模板操作 */
    handleDownloadTemplate() {
      this.download('base/station/downloadTemplate', { ...this.queryParams }, `城市管理模板_${new Date().getTime()}.xlsx`);
    },
    // 显示示例图片
    showExampleImage() {
      this.exampleImageVisible = true;
    },
    // 添加监听城市名称变化的方法
    handleNameChange(value) {
      if (value) {
        // 获取完整拼音
        this.form.namePinyin = pinyin(value, { toneType: 'none' }).replace(/\s/g, '');
        // 获取首字母
        this.form.namePy = pinyin(value, { pattern: 'first', toneType: 'none' }).replace(/\s/g, '');
      } else {
        this.form.namePinyin = '';
        this.form.namePy = '';
      }
    },
    /** 查询车站管理列表 */
    getList() {
      this.loading = true;
      listStation(this.queryParams).then(response => {
        this.stationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        namePinyin: null,
        namePy: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.names = selection.map(item => item.name)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加城市管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStation(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改城市管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names=row.name || this.names;
      this.$modal.confirm('是否确认删除城市名称为"' + names + '"的数据项？').then(function () {
        return delStation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.importOpen = true;
      this.title = "数据导入";
    },
    submitUpload() {
      this.$refs.upload.submit();
      this.importOpen = false;
    },
    // 上传成功回调
    handleExcelSuccess(response, file) {
      this.importOpen = false;
      this.$refs.upload.clearFiles();

      // 检查是否有部分导入失败
      if (response.code === 500 && response.data) {
        // 处理错误数据，确保每个字段都有值且0值不被替换
        this.importErrorData = response.data.map(item => {
          return {
            rowNum: item.rowNum !== undefined ? item.rowNum : null,
            id: item.id, // 保留ID字段
            name: item.name || '',
            namePinyin: item.namePinyin || '',
            namePy: item.namePy || '', // 添加首字母字段
            errorMsg: item.errorMsg || "数据验证失败"
          };
        });

        // 设置状态变量，不自动弹出对话框
        this.showImportError = true;

        // 显示导入结果提示
        this.$modal.msgError({
          message: `导入失败：${this.importErrorData.length}条数据有误，您可以"导出错误数据"或"复制到剪贴板"进行查看和处理`,
          type: 'error',
          duration: 5000,
          showClose: true
        });

        this.getList(); // 刷新列表
      } else {
        this.$alert("导入成功", "导入结果");
        this.getList();
      }
    },
    // 上传失败回调
    handleExcelError(err, file) {
      this.$modal.msgError("上传Excel失败，请重试");
      this.$refs.upload.clearFiles(); // 清空已上传的文件列表
    },
    // 上传前的文件校验
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isExcel) {
        this.$message.error('只能上传Excel文件!');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过5MB!');
        return false;
      }
      return isExcel && isLt5M;
    },
    // 文件超出数量限制时的处理
    handleExceed(files, fileList) {
      this.$message.warning('只能上传一个文件');
    },
    handleFileChange(file, fileList) {
      this.fileSelected = fileList.length > 0;
    },
    /** 导出按钮操作 */
    handleExport() {
      // 创建一个新的对象，复制queryParams中的所有属性
      const exportParams = { ...this.queryParams };
      // 删除分页相关参数
      delete exportParams.pageNum;
      delete exportParams.pageSize;

      this.download('base/station/export', exportParams, `城市管理_${new Date().getTime()}.xlsx`)
    },
    // 导出实际的错误数据
    handleExportErrorData() {
      this.$modal.loading("正在导出数据，请稍候...");

      // 确保每条错误记录都有ID
      const processedData = this.importErrorData.map(item => {
        // 创建新对象，避免直接修改原数据
        const newItem = { ...item };

        // 确保每个记录都有id
        if (!newItem.id) {
          // 使用当前时间戳作为ID
          newItem.id = Date.now();
        }

        return newItem;
      });

      // 直接传递处理后的错误数据到后端
      const formData = new FormData();
      formData.append("errorData", JSON.stringify(processedData));

      // 发送POST请求
      fetch(process.env.VUE_APP_BASE_API + "/base/station/exportErrorData", {
        method: "POST",
        body: formData,
        headers: {
          // 添加认证token
          "Authorization": "Bearer " + this.$store.getters.token
        }
      })
        .then(response => {
          if (response.ok) {
            return response.blob();
          }
          throw new Error("导出失败");
        })
        .then(blob => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.style.display = "none";
          a.href = url;
          a.download = "城市导入错误数据_" + new Date().getTime() + ".xlsx";
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          this.$modal.closeLoading();
        })
        .catch(error => {
          console.error("导出错误:", error);
          this.$modal.closeLoading();
          this.$modal.msgError("导出失败");
        });
    },
    // 复制错误数据到剪贴板
    handleCopyErrorData() {
      try {
        const formattedData = this.importErrorData.map(item => {
          return `ID: ${item.id || '-'}, 城市名称: ${item.name || '-'}, 拼音: ${item.namePinyin || '-'}, 首字母: ${item.namePy || '-'}, 错误原因: ${item.errorMsg || '未知错误'}`;
        }).join('\n');

        const textArea = document.createElement('textarea');
        textArea.value = formattedData;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);

        this.$message({
          message: '已复制到剪贴板',
          type: 'success'
        });
      } catch (err) {
        this.$message.error('复制失败');
        console.error('复制失败:', err);
      }
    },
    /** 清空数据按钮操作 */
    handleClear() {
      this.passwordDialogVisible = true;
      this.passwordForm.password = '';
    },
    /** 提交密码验证 */
    submitPassword() {
      this.$refs["passwordForm"].validate(valid => {
        if (valid) {
          // 将密码包装成对象
          const passwordData = {
            password: this.passwordForm.password
          };
          clearStation(passwordData).then(response => {
            this.$modal.msgSuccess("清空成功");
            this.passwordDialogVisible = false;
            // 清空密码输入框
            this.passwordForm.password = '';
            this.getList();
          }).catch(error => {
            this.$modal.msgError("密码验证失败");
          });
        }
      });
    },
    // 添加关闭密码对话框时重置密码的方法
    handleClosePasswordDialog() {
      this.passwordDialogVisible = false;
      this.passwordForm.password = '';
    },
  }
};
</script>

<style scoped>
/* 保留基本样式 */
.el-table {
  width: 100% !important;
}

/* 紧凑型表格样式 */
.compact-table {
  width: 400px;
  border-collapse: collapse;
  border: 1px solid #EBEEF5;
  table-layout: fixed;
}

.compact-table th,
.compact-table td {
  border: 1px solid #EBEEF5;
  padding: 5px;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.compact-table th {
  background-color: #F5F7FA;
  font-weight: bold;
  font-size: 13px;
}

/* 对话框样式 */
:deep(.zero-padding-dialog .el-dialog__body) {
  padding: 5px !important;
}

:deep(.zero-padding-dialog .el-dialog__header) {
  padding: 10px !important;
}

/* 警告文字样式 */
.warning-text {
  color: #F56C6C;
  font-size: 12px;
  margin-top: 5px;
  text-align: left;
}
</style>
